// pages/function_test/dial_operate/dial_add_background/index.ts

import { bmpConvert } from "../../../../../jl_lib/jl_bmpConvert_1.0.0";
import { BmpConvertManager, BmpConvertType, CallBack, ConversionResult, ConvertParam, Result } from "../../../../../lib/BmpConvertManager";
import { workerInstance } from "../../../../../tools/WorkerManager";
import { ab2hex } from "../../../../../utils/log";
const i18n = require('../../../../../i18n/index');

var lastTouchPoint = { x: 0, y: 0 };
var oldDist = 0;
var eventChannel: WechatMiniprogram.EventChannel;
Page({

    /**
     * 页面的初始数据
     */
    data: {
        devScreenWidth: 240,
        devScreenHeight: 240, // 修改为 240x240 正方形 - 与设备一致
        // 多语言文本
        l10n: {}
    },
    //br23 - 修改为圆形 240x240 - 与设备一致
    devScreenWidth: 240,
    devScreenHeight: 240,
    devScale: 1,
    bmpConvertManager: <BmpConvertManager | undefined>undefined,

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad(option) {
        console.log("裁剪页面接收参数:", option)
        this.imagePath = decodeURIComponent(option.imagePath || '')
        eventChannel = this.getOpenerEventChannel()
        
        // 使用传入的尺寸参数，如果没有则使用默认值
        this.devScreenWidth = parseInt(option.width || '240')
        this.devScreenHeight = parseInt(option.height || '240')
        console.log("devScreenWidth : " + this.devScreenWidth);
        console.log("devScreenHeight : " + this.devScreenHeight);
        console.log("imagePath : " + this.imagePath);

        this.setData(({
            devScreenWidth: this.devScreenWidth,
            devScreenHeight: this.devScreenHeight,
        }))

        // 初始化多语言文本
        this.updateTexts()
    },
    onShow() {
        this.updateTexts()
    },
    onUnload() {
        this.bmpConvertManager?.release()
    },
    canvasHeight: 0,
    canvasWidth: 0,
    dpr: 1,
    onReady() {
        this.screenWidth = wx.getSystemInfoSync().windowWidth;
        this.dpr = wx.getWindowInfo().pixelRatio
        console.log("准备加载图片:", this.imagePath)
        wx.getImageInfo({
            src: this.imagePath, 
            success: (e) => {
                console.log("图片信息获取成功:", e)
                this.baseWidth = e.width
                this.baseHeight = e.height
                this.imgLoad()
            },
            fail: (err) => {
                console.error("图片信息获取失败:", err)
                wx.showToast({
                    title: i18n.t('dialCut.imageLoadFailed'),
                    icon: 'none'
                })
            }
        })
    },
    // 多语言：构建并更新文案
    updateTexts() {
        const l10n = {
            cancel: i18n.t('common.cancel'),
            select: i18n.t('dialCut.select')
        }
        try { wx.setNavigationBarTitle({ title: i18n.t('dialCut.title') }) } catch (e) {}
        this.setData({ l10n })
    },
    imgLoad() {
        const query = wx.createSelectorQuery();
        query.select('#test').boundingClientRect((res) => {
            console.log("this.canvasWidth " + res.width);

            this.devScale = (0.64 * res.width) / 240 // 使用 240 作为基准（圆形直径）
            this.canvasHeight = res.height / this.devScale
            this.canvasWidth = res.width / this.devScale
            this.boxWidth = 240  // 圆形裁剪区域直径
            this.boxHeight = 240 // 圆形裁剪区域直径
            //对canvas进行scale

            if (this.baseHeight > this.baseWidth) {//图片原始高度大于宽度
                this.multiple = this.baseWidth / this.boxWidth // 计算原图和默认显示的倍数
                this.initHeight = this.baseHeight / this.multiple
                this.initWidth = this.boxWidth
                this.transferOffset.x = (this.canvasWidth - this.boxWidth) / 2
                this.transferOffset.y = -(this.initHeight - this.canvasHeight) / 2
            } else {//图片原始宽度大于高度
                this.multiple = this.baseHeight / this.boxHeight // 计算原图和默认显示的倍数
                this.initHeight = this.boxHeight
                this.initWidth = this.baseWidth / this.multiple
                this.transferOffset.x = -(this.initWidth - this.canvasWidth) / 2
                this.transferOffset.y = (this.canvasHeight - this.boxHeight) / 2
            }
            this.scaleHeight = this.initHeight
            this.scaleWidth = this.initWidth
            this.createImage(this.transferOffset)
        }).exec()
    },
    
    createImage(transfer: { x: number, y: number }, isMoving: boolean = false) {
        //判断越界 - 修正像素坐标系偏移
        const circleRadius = (this.devScreenWidth - 1) / 2 // 圆形半径，考虑像素从0开始
        const circleCenterX = (this.canvasWidth - 1) / 2 // 圆心X坐标，考虑像素从0开始
        const circleCenterY = (this.canvasHeight - 1) / 2 // 圆心Y坐标，考虑像素从0开始
        
        const ctx = wx.createCanvasContext('shareFrends')
        ctx.scale(this.devScale, this.devScale)
        
        let translateX = 0
        let translateY = 0
        let rotateAngle = 0
        //旋转,保持中心的东西一直在中心
        switch (this.direction) {
            case 0://不变
                break;
            case 1://逆时针90度
                translateX = 0.5 * (this.canvasWidth - this.canvasHeight)
                translateY = 0.5 * (this.canvasHeight + this.canvasWidth)
                rotateAngle = -90
                break;
            case 2://逆时针180度
                translateX = this.canvasWidth
                translateY = this.canvasHeight
                rotateAngle = -180
                break;
            case 3://逆时针270度
                translateX = 0.5 * (this.canvasHeight + this.canvasWidth)
                translateY = 0.5 * (this.canvasHeight - this.canvasWidth)
                rotateAngle = -270
                break;
            default:
                break;
        }

        ctx.translate(translateX, translateY);
        ctx.rotate(rotateAngle * Math.PI / 180)

        console.log("transfer.x : " + transfer.x);
        console.log("transfer.y : " + transfer.y);
        
        // 绘制完整图片
        ctx.globalAlpha = 1
        ctx.drawImage(this.imagePath, transfer.x, transfer.y, this.scaleWidth, this.scaleHeight);

        //还原ctx角度
        ctx.rotate(-rotateAngle * Math.PI / 180)
        ctx.translate(-translateX, -translateY);

        // 绘制圆形外的遮罩区域 - 使用传统方法避免透明度问题
        ctx.globalAlpha = 0.6
        ctx.fillStyle = '#808080'
        
        // 绘制四个矩形来覆盖圆形外的区域
        // 上方遮罩
        ctx.fillRect(0, 0, this.canvasWidth, circleCenterY - circleRadius)
        // 下方遮罩
        ctx.fillRect(0, circleCenterY + circleRadius, this.canvasWidth, this.canvasHeight - (circleCenterY + circleRadius))
        // 左侧遮罩
        ctx.fillRect(0, circleCenterY - circleRadius, circleCenterX - circleRadius, 2 * circleRadius)
        // 右侧遮罩
        ctx.fillRect(circleCenterX + circleRadius, circleCenterY - circleRadius, this.canvasWidth - (circleCenterX + circleRadius), 2 * circleRadius)
        
        // 绘制四个角的遮罩 - 动态步长优化性能
        const step = isMoving ? 12 : 6 // 移动时使用更大步长提高流畅性
        
        // 左上角遮罩 - 优化性能避免开方运算
        const radiusSquared = circleRadius * circleRadius
        for (let x = circleCenterX - circleRadius; x < circleCenterX; x += step) {
            for (let y = circleCenterY - circleRadius; y < circleCenterY; y += step) {
                const dx = x - circleCenterX
                const dy = y - circleCenterY
                const distanceSquared = dx * dx + dy * dy // 避免开方运算提高性能
                if (distanceSquared > radiusSquared) {
                    ctx.fillRect(x, y, step, step)
                }
            }
        }
        
        // 右上角遮罩
        for (let x = circleCenterX; x < circleCenterX + circleRadius; x += step) {
            for (let y = circleCenterY - circleRadius; y < circleCenterY; y += step) {
                const dx = x - circleCenterX
                const dy = y - circleCenterY
                const distanceSquared = dx * dx + dy * dy // 避免开方运算提高性能
                if (distanceSquared > radiusSquared) {
                    ctx.fillRect(x, y, step, step)
                }
            }
        }
        
        // 左下角遮罩
        for (let x = circleCenterX - circleRadius; x < circleCenterX; x += step) {
            for (let y = circleCenterY; y < circleCenterY + circleRadius; y += step) {
                const dx = x - circleCenterX
                const dy = y - circleCenterY
                const distanceSquared = dx * dx + dy * dy // 避免开方运算提高性能
                if (distanceSquared > radiusSquared) {
                    ctx.fillRect(x, y, step, step)
                }
            }
        }
        
        // 右下角遮罩
        for (let x = circleCenterX; x < circleCenterX + circleRadius; x += step) {
            for (let y = circleCenterY; y < circleCenterY + circleRadius; y += step) {
                const dx = x - circleCenterX
                const dy = y - circleCenterY
                const distanceSquared = dx * dx + dy * dy // 避免开方运算提高性能
                if (distanceSquared > radiusSquared) {
                    ctx.fillRect(x, y, step, step)
                }
            }
        }

        // 绘制圆形边框 - 移动时简化
        ctx.globalAlpha = 1
        ctx.beginPath()
        ctx.arc(circleCenterX, circleCenterY, circleRadius - 0.5, 0, 2 * Math.PI) // 稍微缩小半径避免毛边
        ctx.strokeStyle = '#FFFFFF'
        ctx.lineWidth = 1.5 // 稍微细一点的线条
        ctx.stroke()
        
        if (!isMoving) {
            // 仅在非移动时添加内圈边框增强效果
            ctx.beginPath()
            ctx.arc(circleCenterX, circleCenterY, circleRadius - 1.5, 0, 2 * Math.PI)
            ctx.strokeStyle = 'rgba(255, 255, 255, 0.3)'
            ctx.lineWidth = 0.5
            ctx.stroke()
        }

        ctx.draw()
    },
    touchstart(e: WechatMiniprogram.TouchEvent) {
        console.log("开始点击" + e.touches[0].clientX + " , " + e.touches[0].clientY);
        lastTouchPoint = { x: 0, y: 0 }
        if (e.touches.length > 1) {
            oldDist = this._spacing(e)
            //计算中心点
            var centerX = (e.touches[0].clientX + e.touches[1].clientX) / 2;
            var centerY = (e.touches[0].clientY + e.touches[1].clientY) / 2;
            //根据中心点计算出，图片的中心点，然后保持中心点位置不变
            //canvas宽高不变
            console.log("centerX : " + centerX + ", centerY: " + centerY);
            this.lastTouchDetailArray = e.touches
        }
    },
    ni: 0,
    direction: 0,//方向
    lastMoveTime: 0, // 上次移动时间，用于节流
    moveThrottle: 16, // 移动节流间隔(ms) - 约60fps
    imagePath: '',//图片路径
    transferOffset: { x: 0, y: 0 },//偏移位置
    scale: 1,//缩放比例
    screenWidth: 100,//屏幕宽度
    multiple: 1,// 计算原图和默认显示的倍数
    baseWidth: 100, // 图片实际宽度
    baseHeight: 100, // 图片实际高度
    initWidth: 100, // 图片默认显示宽度
    initHeight: 100, // 图片默认显示高度
    scaleWidth: 100, // 图片缩放后的宽度
    scaleHeight: 100, // 图片缩放后的高度
    boxWidth: 100,//取景框的宽度
    boxHeight: 100,//取景框的高度
    lastTouchDetailArray: new Array<WechatMiniprogram.TouchDetail>(),//上次双指移动的位置
    touchmove(e: WechatMiniprogram.TouchEvent) {
        // 移动节流优化 - 限制重绘频率提高流畅性
        const currentTime = Date.now()
        if (currentTime - this.lastMoveTime < this.moveThrottle) {
            return // 跳过过于频繁的移动事件
        }
        this.lastMoveTime = currentTime
        
        // console.log("拖动");
        this.ni++
        switch (e.touches.length) {
            case 1://单指只有拖动
                if (lastTouchPoint.x == 0 && lastTouchPoint.y == 0) {
                    lastTouchPoint.x = e.touches[0].clientX
                    lastTouchPoint.y = e.touches[0].clientY
                } else {
                    var xOffset = Math.round(e.touches[0].clientX - lastTouchPoint.x) // 整数像素对齐
                    var yOffset = Math.round(e.touches[0].clientY - lastTouchPoint.y) // 整数像素对齐
                    lastTouchPoint.x = e.touches[0].clientX
                    lastTouchPoint.y = e.touches[0].clientY
                    switch (this.direction) {
                        case 0://不变
                            this.transferOffset.x = Math.round(this.transferOffset.x + xOffset) // 整数像素对齐
                            this.transferOffset.y = Math.round(this.transferOffset.y + yOffset) // 整数像素对齐
                            break;
                        case 1://逆时针90度
                            //旋转第一种情况
                            this.transferOffset.x = Math.round(this.transferOffset.x + (-yOffset))
                            this.transferOffset.y = Math.round(this.transferOffset.y + xOffset)
                            break;
                        case 2://逆时针180度
                            //旋转第2种情况
                            this.transferOffset.x = Math.round(this.transferOffset.x + (-xOffset))
                            this.transferOffset.y = Math.round(this.transferOffset.y + (-yOffset))
                            break;
                        case 3:
                            //逆时针270度
                            this.transferOffset.x = Math.round(this.transferOffset.x + yOffset)
                            this.transferOffset.y = Math.round(this.transferOffset.y + (-xOffset))
                            break;
                        default:
                            break;
                    }
                    this.createImage(this.transferOffset, true) // 移动时使用简化模式
                    // console.log("lastTouchPoint ", this.transferOffset);
                }
                break;
            case 2://双指有拖动和放大缩小
                //需要区分当前动作是放大缩小还是拖动
                const dValueX0 = e.touches[0].clientX - this.lastTouchDetailArray[0].clientX
                const dValueY0 = e.touches[0].clientY - this.lastTouchDetailArray[0].clientY
                const dValueX1 = e.touches[1].clientX - this.lastTouchDetailArray[1].clientX
                const dValueY1 = e.touches[1].clientY - this.lastTouchDetailArray[1].clientY
                this.lastTouchDetailArray = e.touches
                // 简化方向判断逻辑 - 手机操作优化
                const isSameDirectionX = (dValueX0 * dValueX1 >= 0) // 同向或其中一个为0
                const isSameDirectionY = (dValueY0 * dValueY1 >= 0) // 同向或其中一个为0
                // console.log("dValueX0 ：", dValueX0);
                // console.log("dValueY0 ：", dValueY0);
                // console.log("dValueX1 ：", dValueX1);
                // console.log("dValueY1 ：", dValueY1);
                // 简化手势识别逻辑 - 手机操作优化
                let type = 1 // 0:拖动，1：缩放
                const moveThreshold = 3 // 移动阈值，小于此值认为是静止
                const isStatic0 = Math.abs(dValueX0) < moveThreshold && Math.abs(dValueY0) < moveThreshold
                const isStatic1 = Math.abs(dValueX1) < moveThreshold && Math.abs(dValueY1) < moveThreshold
                
                if (isStatic0 || isStatic1) {
                    // 有一根手指基本静止，认为是缩放
                    type = 1
                } else if (isSameDirectionX && isSameDirectionY) {
                    // 两根手指同向移动，认为是拖动
                    type = 0
                }
                console.log("type ：", type);

                if (type == 1) {//缩放
                    let distance = this._spacing(e);
                    // 计算移动的过程中实际移动了多少的距离
                    let distanceDiff = distance - oldDist;
                    oldDist = distance; // 更新距离
                    let newScale = this.scale + 0.001 * distanceDiff; // 提高缩放灵敏度
                    console.log(" newScale " + newScale);
                    console.log(" multiple " + this.multiple);
                    if (newScale >= this.multiple && this.multiple > 2) { // 原图比较大情况
                        newScale = this.multiple;
                        console.log(" 原图比较大情况 ");
                    } else if (this.multiple < 2 && newScale >= 2) { // 原图较小情况
                        newScale = 2; // 最大2倍
                        console.log(" 最大2倍 ");
                    };
                    // // 最小缩放到1
                    if (newScale <= 1) {
                        newScale = 1;
                    };
                    this.scale = newScale
                    this.scaleWidth = newScale * this.initWidth;
                    this.scaleHeight = newScale * this.initHeight;
                    this.createImage(this.transferOffset, true) // 缩放时使用简化模式
                } else {//拖动
                    let xOffset = Math.round(dValueX1) // 整数像素对齐
                    let yOffset = Math.round(dValueY1) // 整数像素对齐
                    if (Math.abs(dValueX0) > Math.abs(dValueX1)) {//选绝对值最大的
                        xOffset = Math.round(dValueX0)
                    }
                    if (Math.abs(dValueY0) > Math.abs(dValueY1)) {//选绝对值最大的
                        yOffset = Math.round(dValueY0)
                    }
                    switch (this.direction) {
                        case 0://不变
                            this.transferOffset.x = Math.round(this.transferOffset.x + xOffset)
                            this.transferOffset.y = Math.round(this.transferOffset.y + yOffset)
                            break;
                        case 1://逆时针90度
                            //旋转第一种情况
                            this.transferOffset.x = Math.round(this.transferOffset.x + (-yOffset))
                            this.transferOffset.y = Math.round(this.transferOffset.y + xOffset)
                            break;
                        case 2://逆时针180度
                            //旋转第2种情况
                            this.transferOffset.x = Math.round(this.transferOffset.x + (-xOffset))
                            this.transferOffset.y = Math.round(this.transferOffset.y + (-yOffset))
                            break;
                        case 3:
                            //逆时针270度
                            this.transferOffset.x = Math.round(this.transferOffset.x + yOffset)
                            this.transferOffset.y = Math.round(this.transferOffset.y + (-xOffset))
                            break;
                        default:
                            break;
                    }
                    this.createImage(this.transferOffset, true) // 拖动时使用简化模式
                }
                break;
            default:
                break;
        }
    },
    touchend(_e: WechatMiniprogram.TouchEvent) {
        console.log("拖动结束");
        // 移动结束后重新绘制高质量版本
        this.createImage(this.transferOffset, false)
    },
    clickCancel(_e: WechatMiniprogram.BaseEvent) {
        wx.navigateBack()
    },
    clickOverturn() {
        this.direction = (this.direction + 1) % 4
        this.createImage(this.transferOffset)
    },
    clickSelect() {
        const transfer = this.transferOffset
        const circleRadius = (this.devScreenWidth - 1) / 2 // 圆形半径，考虑像素从0开始
        const circleCenterX = (this.canvasWidth - 1) / 2 // 圆心X坐标，考虑像素从0开始
        const circleCenterY = (this.canvasHeight - 1) / 2 // 圆心Y坐标，考虑像素从0开始
        
        const ctx = wx.createCanvasContext('shareFrends')
        ctx.scale(this.devScale, this.devScale)

        let translateX = 0
        let translateY = 0
        let rotateAngle = 0
        //旋转,保持中心的东西一直在中心
        switch (this.direction) {
            case 0://不变
                break;
            case 1://逆时针90度
                translateX = 0.5 * (this.canvasWidth - this.canvasHeight)
                translateY = 0.5 * (this.canvasHeight + this.canvasWidth)
                rotateAngle = -90
                break;
            case 2://逆时针180度
                translateX = this.canvasWidth
                translateY = this.canvasHeight
                rotateAngle = -180
                break;
            case 3://逆时针270度
                translateX = 0.5 * (this.canvasHeight + this.canvasWidth)
                translateY = 0.5 * (this.canvasHeight - this.canvasWidth)
                rotateAngle = -270
                break;
            default:
                break;
        }

        ctx.translate(translateX, translateY);
        ctx.rotate(rotateAngle * Math.PI / 180)

        console.log("transfer.x : " + transfer.x);
        console.log("transfer.y : " + transfer.y);

        ctx.globalAlpha = 1
        ctx.drawImage(this.imagePath, transfer.x, transfer.y, this.scaleWidth, this.scaleHeight);

        //还原ctx角度
        ctx.rotate(-rotateAngle * Math.PI / 180)
        ctx.translate(-translateX, -translateY);

        // 简单绘制圆形边框作为预览指示 - 抗锯齿处理
        ctx.globalAlpha = 1
        ctx.beginPath()
        ctx.arc(circleCenterX, circleCenterY, circleRadius - 0.5, 0, 2 * Math.PI) // 稍微缩小半径避免毛边
        ctx.strokeStyle = '#FFFFFF'
        ctx.lineWidth = 1.5 // 稍微细一点的线条
        ctx.stroke()
        
        // 添加内圈边框增强效果
        ctx.beginPath()
        ctx.arc(circleCenterX, circleCenterY, circleRadius - 1.5, 0, 2 * Math.PI)
        ctx.strokeStyle = 'rgba(255, 255, 255, 0.3)'
        ctx.lineWidth = 0.5
        ctx.stroke()
        
        ctx.draw()
        //用另一个canvas放大图片获取
        let translateX2 = 0
        let translateY2 = 0
        let rotateAngle2 = 0
        switch (this.direction) {
            case 0://不变

                break;
            case 1://逆时针90度
                //旋转第一种情况
                translateX2 = 0.5 * (this.devScreenWidth - this.devScreenHeight)
                translateY2 = 0.5 * (this.devScreenHeight + this.devScreenWidth)
                rotateAngle2 = -90
                break;
            case 2://逆时针180度
                //旋转第2种情况
                translateX2 = this.devScreenWidth
                translateY2 = this.devScreenHeight
                rotateAngle2 = -180
                break;
            case 3:
                //逆时针270度
                translateX2 = 0.5 * (this.devScreenHeight + this.devScreenWidth)
                translateY2 = 0.5 * (this.devScreenHeight - this.devScreenWidth)
                rotateAngle2 = -270
                break;
            default:
                break;
        }
        const ctx2 = wx.createCanvasContext('shareFrends2')
        ctx2.scale(this.devScale, this.devScale)
        ctx2.translate(translateX2, translateY2);
        ctx2.rotate(rotateAngle2 * Math.PI / 180)
        
        // 对于圆形裁剪，我们需要重新计算图片的位置
        // 圆形的边距计算（圆形在画布中心）
        const circleMarginHorizontal = (this.canvasWidth - this.devScreenWidth) / 2
        const circleMarginVertical = (this.canvasHeight - this.devScreenHeight) / 2
        
        // 使用与设备端一致的算法：先绘制图片，再用像素级方法进行圆形裁剪
        // 第1步：绘制完整图片到240x240区域
        switch (this.direction) {
            case 0:
                ctx2.drawImage(this.imagePath, ((transfer.x - circleMarginHorizontal) / (this.devScale)), ((transfer.y - circleMarginVertical) / (this.devScale)), (this.scaleWidth / (this.devScale)), (this.scaleHeight / (this.devScale)));
                break;
            case 1:
                ctx2.drawImage(this.imagePath, ((transfer.x) / (this.devScale)), 0, (this.scaleWidth / (this.devScale)), (this.scaleHeight / (this.devScale)));
                break;
            default:
                ctx2.drawImage(this.imagePath, ((transfer.x) / (this.devScale)), ((transfer.y) / (this.devScale)), (this.scaleWidth / (this.devScale)), (this.scaleHeight / (this.devScale)));
                break;
        }

   
        ctx2.draw(false, () => {
            // 等待一小段时间确保绘制完成
            setTimeout(() => {
                wx.canvasGetImageData({
                canvasId: 'shareFrends2',
                x: 0,
                y: 0,
                width: this.devScreenWidth,
                height: this.devScreenHeight,
                success: (res) => {
                    const tempData = res.data
                    const data = new Uint8Array(tempData.byteLength)
                    
                    // 圆形裁剪参数 - 修正像素坐标系偏移
                    const centerX = (this.devScreenWidth - 1) / 2  // 像素坐标从0开始，所以是(240-1)/2 = 119.5
                    const centerY = (this.devScreenHeight - 1) / 2 // 像素坐标从0开始，所以是(240-1)/2 = 119.5
                    const radius = (this.devScreenWidth - 1) / 2   // 半径也要相应调整
                    
                    for (let index = 0; index < tempData.byteLength; index += 4) {
                        const pixelIndex = index / 4
                        const x = pixelIndex % this.devScreenWidth
                        const y = Math.floor(pixelIndex / this.devScreenWidth)
                        
                        // 计算像素到圆心的距离
                        const dx = x - centerX
                        const dy = y - centerY
                        const distance = Math.sqrt(dx * dx + dy * dy)
                        
                        const r = tempData[index];
                        const g = tempData[index + 1];
                        const b = tempData[index + 2];
                        const a = tempData[index + 3];
                        
                        if (distance <= radius - 2) {
                            // 圆形内部：保持原色
                            data[index] = b
                            data[index + 1] = g
                            data[index + 2] = r
                            data[index + 3] = a
                        } else if (distance <= radius) {
                            // 边缘抗锯齿：使用更平滑的渐变
                            const edgeWidth = 2 // 边缘渐变宽度
                            const alpha = Math.max(0, (radius - distance) / edgeWidth) // 平滑渐变
                            const smoothAlpha = alpha * alpha * (3 - 2 * alpha) // 三次贝塞尔曲线平滑
                            
                            data[index] = Math.round(b * smoothAlpha)     // B
                            data[index + 1] = Math.round(g * smoothAlpha) // G
                            data[index + 2] = Math.round(r * smoothAlpha) // R
                            data[index + 3] = 255 // A - 不透明
                        } else {
                            // 圆形外部：设为黑色（与设备端一致）
                            data[index] = 0     // B
                            data[index + 1] = 0 // G
                            data[index + 2] = 0 // R
                            data[index + 3] = 255 // A - 不透明
                        }
                    }
                    this._bmpConvert(data, this.devScreenWidth, this.devScreenHeight)
                }, fail: (error) => {
                    console.error("canvasGetImageData fail :", error);
                }
            })
            }, 100); // 等待100ms确保绘制完成
        })
    },
    _bmpConvert(data: Uint8Array, width: number, height: number) {
        console.log("bmpConvert data :", data);
        
        // 🆕 在转换为BMP之前，先保存裁剪后的圆形图片为临时PNG文件
        this._saveCroppedImageAsPng().then((tempImagePath) => {
            console.log('✅ 裁剪后的图片已保存为临时PNG文件:', tempImagePath);
            
            // 将临时图片路径存储到全局变量中
            const app = getApp();
            app.globalData = app.globalData || {};
            app.globalData.tempDialBgImagePath = tempImagePath;
            console.log('💾 已保存临时图片路径到全局变量:', tempImagePath);
            
            // 继续原有的BMP转换流程
            this._proceedWithBmpConvert(data, width, height);
            
        }).catch((error) => {
            console.error('❌ 保存临时PNG图片失败:', error);
            // 即使保存PNG失败，也要继续BMP转换流程
            this._proceedWithBmpConvert(data, width, height);
        });
    },
    
    // 🆕 保存裁剪后的圆形图片为PNG文件
    async _saveCroppedImageAsPng(): Promise<string> {
        return new Promise((resolve, reject) => {
            console.log('🖼️ [_saveCroppedImageAsPng] 开始保存裁剪后的图片为PNG');
            
            // 等待当前的画布绘制完成，然后导出PNG
            setTimeout(() => {
                wx.canvasToTempFilePath({
                    canvasId: 'shareFrends2',
                    x: 0,
                    y: 0,
                    width: this.devScreenWidth,
                    height: this.devScreenHeight,
                    fileType: 'png',
                    quality: 0.9, // PNG质量设置
                    success: (res) => {
                        console.log('✅ PNG图片导出成功:', res.tempFilePath);
                        resolve(res.tempFilePath);
                    },
                    fail: (error) => {
                        console.error('❌ PNG图片导出失败:', error);
                        reject(error);
                    }
                });
            }, 200); // 等待足够时间确保画布绘制完成
        });
    },
    
    // 🆕 继续原有的BMP转换流程
    _proceedWithBmpConvert(data: Uint8Array, width: number, height: number) {
        console.log('🔄 继续BMP转换流程');
        
        this.bmpConvertManager = new BmpConvertManager(workerInstance)
        const in_buffer = data;
        const callback: CallBack = new CallBack();
        callback.onStart = () => {
            wx.showLoading({ title: i18n.t('dialCut.converting') })
        }
        callback.onFinished = (result: ConversionResult) => {
            const output_buf = result.output_buf;
            const resultCode = result.result;
            if ((resultCode != undefined && resultCode >= Result.RESULT_SUCCESS) && output_buf != undefined) {
                wx.hideLoading()
                // 先设置全局变量，再跳转页面
                const app = getApp()
                app.globalData = app.globalData || {}
                app.globalData.dialBgData = output_buf
                console.log('设置全局变量dialBgData成功，数据大小:', output_buf.byteLength)
                console.log('全局数据对象:', app.globalData)
                
                // 直接跳转到dial_add_background页面
                wx.redirectTo({
                    url: '/pages/function_test/dial_operate/dial_add_background/index?fromCut=true',
                    success: () => {
                        console.log('跳转到dial_add_background页面成功')
                    },
                    fail: (error) => {
                        console.error('跳转到dial_add_background页面失败:', error)
                    }
                })
            } else {
                wx.showToast({ title: i18n.t('dialCut.convertFailed'), icon: "error" })
            }
        }
        const convertParam = new ConvertParam()
        convertParam.format = ConvertParam.FORMAT_AUTO; // Example default
        this.bmpConvertManager.bitmapConvert(BmpConvertType.TYPE_707N_RGB, in_buffer, width, height, convertParam, callback)
    },
    /**
 * 计算两指间距
 */
    _spacing(event: WechatMiniprogram.TouchEvent) {
        var x = event.touches[0].clientX - event.touches[1].clientX;
        var y = event.touches[0].clientY - event.touches[1].clientY;
        return Math.sqrt(x * x + y * y);
    },
})
